package com.kordar.admin.kernel.wrapper;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kordar.datalist.DataColumn;
import lombok.Data;
import lombok.ToString;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Data
@ToString
public class UpdateWrapperEntity<T> {
    private Map<String, String> conditions;
    private Map<String, String> data;
    private UpdateWrapper<T> query = new UpdateWrapper<>();

    public UpdateWrapperEntity() {
    }

    public UpdateWrapperEntity<T> data() {
        for (Map.Entry<String, String> m : data.entrySet()) {
            this.query = this.query.set(m.getKey(), m.getValue());
        }
        return this;
    }

    public UpdateWrapperEntity<T> where(Class<T> clzz) {

        Map<String, Class<?>> parallel = new HashMap<>();
        Field[] fields = clzz.getDeclaredFields();
        Field field;
        Map<String, String> alias = new HashMap<>();

        for (int i = 0; i < fields.length; i++) {
            try {
                field = fields[i];

                if (field.isAnnotationPresent(DataColumn.class)) {
                    DataColumn annotation = field.getAnnotation(DataColumn.class);
                    if (!"".equals(annotation.alias().trim())) {

                        if (field.isAnnotationPresent(TableId.class)) {
                            alias.put(annotation.alias().trim(), field.getAnnotation(TableId.class).value());
                        } else if (field.isAnnotationPresent(TableField.class)) {
                            alias.put(annotation.alias().trim(), field.getAnnotation(TableField.class).value());
                        } else {
                            alias.put(annotation.alias().trim(), field.getName());
                        }
                    }
                }

                field.setAccessible(true); // 开启访问权限
                parallel.put(field.getName(), field.getType());
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        // System.out.println(alias);


        for (Map.Entry<String, String> m : conditions.entrySet()) {
            String value = m.getValue();
            String key = alias.getOrDefault(m.getKey(), m.getKey());
            Class<?> type = parallel.get(key);
            if (!value.isEmpty()) {
                if (type == Integer.class) {
                    this.query = this.query.eq(key, Integer.parseInt(value));
                } else if (type == Long.class) {
                    this.query = this.query.eq(key, Long.valueOf(value));
                } else {
                    this.query = this.query.eq(key, value);
                }
            }
        }
        return this;
    }
}
